﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Threading;

namespace Base.ModuleBase.Attachs
{
    public class ClickIntervalAttach
    {
        #region Public 方法

        /// <summary>
        /// Returns the value of the IntervalTimeProperty
        /// </summary>
        /// <param name="obj">The dependency-object whichs value should be returned</param>
        /// <returns>The value of the given property</returns>
        public static int GetIntervalTime(DependencyObject obj)
        {
            return (int)obj.GetValue(IntervalTimeProperty);
        }

        /// <summary>
        /// Sets the value of the IntervalTimeProperty
        /// </summary>
        /// <param name="obj">The dependency-object whichs value should be set</param>
        /// <param name="value">The value which should be assigned to the IntervalTimeProperty</param>
        public static void SetIntervalTime(DependencyObject obj, int value)
        {
            obj.SetValue(IntervalTimeProperty, value);
        }

        #endregion Public 方法

        /// <summary>
        /// 点击间隔时间，最低100ms
        /// </summary>
        public static readonly DependencyProperty IntervalTimeProperty = DependencyProperty.RegisterAttached("IntervalTime",
            typeof(int), typeof(ClickIntervalAttach), new UIPropertyMetadata(100, OnIntervalTimeChanged));

        /// <summary>
        /// 点击间隔时间改变
        /// property was changed
        /// </summary>
        /// <param name="sender">The sender (the UIElement)</param>
        /// <param name="e">Some additional information</param>
        public static void OnIntervalTimeChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            if (sender is UIElement element)
            {
                element.PreviewMouseUp -= element_Click;
                element.PreviewMouseUp += element_Click;
            }
        }

        private static async void element_Click(object sender, RoutedEventArgs e)
        {
            if (sender is UIElement element)
            {
                element.IsEnabled = false;

                var tempIntervalTime = GetIntervalTime(element);
                await Task.Delay(tempIntervalTime);

                element.IsEnabled = true;
            }
        }
    }
}
